import { WindLayer } from 'cesium-wind-layer'
import type { WindLayerOptions, WindData } from 'cesium-wind-layer'
import { colorSchemes } from '@/constants'
import type { IGFSItem } from 'wind-core'
import CesiumWind from '@/utils/windLayer'

async function fetchWindData(): Promise<[WindData & { bbox: number[] }, IGFSItem[]]> {
  try {
    const [partialWindData, globalWindData] = await Promise.all([
      fetch('https://cesium-wind-layer.opendde.com/wind.json').then((res) => res.json()),
      fetch('/wind/2024122600.json').then((res) => res.json())
    ])

    return [partialWindData, globalWindData]
  } catch (error) {
    throw new Error(error instanceof Error ? error.message : 'Failed to fetch wind data')
  }
}

export async function useWindLayer() {
  const [partialWindData, globalWindData] = await fetchWindData()

  // 局部风场
  const windData: WindData = {
    u: partialWindData.u,
    v: partialWindData.v,
    width: partialWindData.width,
    height: partialWindData.height,
    bounds: {
      west: partialWindData.bbox[0],
      south: partialWindData.bbox[1],
      east: partialWindData.bbox[2],
      north: partialWindData.bbox[3]
    }
  }
  const defaultOptions: Partial<WindLayerOptions> = {
    ...WindLayer.defaultOptions,
    particlesTextureSize: 200,
    colors: colorSchemes.find((item) => item.value === 'cool')?.colors.reverse(),
    flipY: true,
    useViewerBounds: true,
    dynamic: true
  }
  const initialOptions = {
    ...defaultOptions,
    domain: {
      min: 0,
      max: 8
    },
    speedFactor: 0.8,
    lineWidth: { min: 1, max: 3 },
    lineLength: { min: 50, max: 100 },
    particleHeight: 100
  }
  const partialWindLayer = new WindLayer(window.viewer, windData, initialOptions)

  // 全球风场
  const windOptions = {
    colorScale: colorSchemes.find((item) => item.value === 'turbo')?.colors.reverse(),
    frameRate: 20,
    maxAge: 60,
    globalAlpha: 0.9,
    velocityScale: 1 / 10,
    paths: 2000
  }
  const globalWindLayer = new CesiumWind(globalWindData, { windOptions })
  globalWindLayer.addTo(window.viewer)

  return { partialWindLayer, globalWindLayer }
}
